<template>
  <teleport to="body">
    <transition name="toast">
      <div v-if="visible" class="toast-container" :class="type">
        <div class="toast-icon">
          <span v-if="type === 'success'">✓</span>
          <span v-else-if="type === 'error'">✕</span>
          <span v-else-if="type === 'info'">ℹ</span>
          <span v-else-if="type === 'warning'">⚠</span>
        </div>
        <div class="toast-message">{{ message }}</div>
      </div>
    </transition>
  </teleport>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'

interface Props {
  message: string
  type?: 'success' | 'error' | 'info' | 'warning'
  duration?: number
  show?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  type: 'info',
  duration: 3000,
  show: false
})

const emit = defineEmits<{
  close: []
}>()

const visible = ref(props.show)
let timer: NodeJS.Timeout | null = null

// 启动定时器
const startTimer = () => {
  console.log('[Toast] 启动定时器, duration:', props.duration, 'ms')
  if (timer) {
    console.log('[Toast] 清除旧定时器')
    clearTimeout(timer)
  }
  
  timer = setTimeout(() => {
    console.log('[Toast] 定时器触发，准备关闭')
    visible.value = false
    emit('close')
  }, props.duration)
  console.log('[Toast] 定时器 ID:', timer)
}

// 监听 show 变化
watch(() => props.show, (newVal) => {
  console.log('[Toast] watch show 变化:', newVal)
  visible.value = newVal
  
  if (newVal) {
    startTimer()
  }
}, { immediate: true })

// 组件挂载时如果是显示状态，启动定时器
onMounted(() => {
  console.log('[Toast] 挂载, show:', props.show, 'message:', props.message)
  if (props.show) {
    startTimer()
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearTimeout(timer)
  }
})
</script>

<style scoped>
.toast-container {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 99999;
  min-width: 200px;
  max-width: 500px;
  pointer-events: auto;
  margin-bottom: 12px;
}

.toast-icon {
  font-size: 20px;
  font-weight: bold;
}

.toast-message {
  font-size: 14px;
  color: white;
  word-break: break-word;
}

.toast-container.success {
  background-color: rgba(76, 175, 80, 0.95);
  color: white;
}

.toast-container.error {
  background-color: rgba(244, 67, 54, 0.95);
  color: white;
}

.toast-container.info {
  background-color: rgba(33, 150, 243, 0.95);
  color: white;
}

.toast-container.warning {
  background-color: rgba(255, 152, 0, 0.95);
  color: white;
}

/* 动画 */
.toast-enter-active,
.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}

.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}
</style>

